package controller;

import appmodel.ControllerEvent;
import appmodel.ControllerEventType;
import appmodel.event.AShapeEvent;
import model.Circle;
import model.Shape;
import model.ShapeType;
import model.Square;
import model.storage.GeneralStorage;
import view.IView;

import java.util.ArrayList;
import java.util.List;

public class Controller implements IController {

    private final GeneralStorage storage;

    private final List<IView> views = new ArrayList<IView>();

    public Controller(GeneralStorage storage) {
        this.storage = storage;
    }

    @Override
    public void registerView(IView view) {
        views.add(view);
    }

    private void sendEventToViews(ControllerEvent event) {
        for (IView view : views) {
            view.onControllerEvent(event);
        }
    }

    @Override
    public void addShape(Shape shape) {
        storage.addShape(shape);
        sendEventToViews(new AShapeEvent(ControllerEventType.ADD_SHAPE, shape));
    }

    @Override
    public void editShape(Shape shape) {
        storage.editShape(shape);
        sendEventToViews(new AShapeEvent(ControllerEventType.EDIT_SHAPE, shape));
    }

    @Override
    public void removeShape(Shape shape) {
        storage.removeShape(shape);
        sendEventToViews(new AShapeEvent(ControllerEventType.REMOVE_SHAPE, shape));
    }

    @Override
    public void removeAll() {
        storage.clear();
        sendEventToViews(new ControllerEvent() {
            @Override
            public ControllerEventType getType() {
                return ControllerEventType.REFRESH;
            }
        });
    }

    @Override
    public List<Circle> getCircles() {
        return storage.getAllForShapeType(ShapeType.CIRCLE);
    }

    @Override
    public List<Square> getSquares() {
        return storage.getAllForShapeType(ShapeType.SQUARE);
    }
}
